package be.phl.mycinema.classes;

import android.app.ActivityManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.util.LruCache;

public class MemoryCache {

	private static MemoryCache memoryCache;
	@SuppressWarnings("rawtypes")
	private static LruCache mMemoryCache;
	
	public MemoryCache() {
		
	}

    @SuppressWarnings("rawtypes")
	public static MemoryCache createMemoryCache(Context context) {
        
        if (memoryCache == null) {
        	memoryCache = new MemoryCache();
        	
        	// memClass = max
        	final int memClass = ((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE))
					.getMemoryClass();

			// 1/8ste van het totale geheugen gebruiken als cache
			final int cacheSize = 1024 * 1024 * memClass / 8;

			mMemoryCache = new LruCache(cacheSize) {

				@SuppressWarnings("unused")
				protected int sizeOf(String key, Bitmap bitmap) {
					// The cache size will be measured in bytes rather than
					// number of items.
					return bitmap.getByteCount();
				}
			};
        }
        
        return memoryCache;
    }

	@SuppressWarnings("unchecked")
	public void addBitmapToMemoryCache(String key, Bitmap bitmap) {
	    if (getBitmapFromMemCache(key) == null) {
	        mMemoryCache.put(key, bitmap);
	    }
	}

	@SuppressWarnings("unchecked")
	public Bitmap getBitmapFromMemCache(String key) {
	    return (Bitmap) mMemoryCache.get(key);
	}
    
}
